#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: sql_injection.py
# Description: 
#   How to implement sql injection and prevent it.
# Edit History: 
#   2011-12-05    File created.
#===============================================================================
import MySQLdb

try:
    conn = MySQLdb.connect (host = "localhost",
    user = "uname",
    passwd = "pass",
    db = "mydb")
    cursor = conn.cursor()
    
    email = "' OR '1'='1"
    # SQL Injection: SELECT * FROM user_info WHERE email = '' OR '1'='1'
    query = "SELECT * FROM user_info WHERE email = '" + email + "'"
    print query
    cursor.execute(query)
    
    if cursor.rowcount > 0:
        print cursor.fetchall()
    else:
        print "no item found"
        
except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])

import MySQLdb

try:
    conn = MySQLdb.connect (host = "localhost",
    user = "uname",
    passwd = "pass",
    db = "mydb")
    cursor = conn.cursor()

    email = "' OR '1'='1"
    # Method1 : Fail Prevent: cursor.execute("... %s ...%s", (param1, param2)), Sucess
    cursor.execute("SELECT * FROM user_info WHERE email = %s", ("' OR '1'='1'"))
    # Method2 : Fail Prevent: cursor.execute("... %s ...%s", (param1, param2)), but it will fail use variable
    cursor.execute("SELECT * FROM user_info WHERE email = %s", (email))
    
    # Method3 :Prevent: cursor.execute("... %s ...%s", (param1, param2))
    cursor.execute("""SELECT * FROM user_info WHERE email = %s""", (email))
    
    if cursor.rowcount > 0:
        print cursor.fetchall()
    else:
        print "no item found"
        
except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])

